//
// Created by 邹迪凯 on 2021/7/17.
//

#ifndef LWPT_DATASOURCE_H
#define LWPT_DATASOURCE_H

#include <fstream>
#include <iostream>
#include <vector>
#include <random>

#include "entity.h"

using namespace std;

class DataSource {
public:
    vector<Location> workers;
    vector<Location> tasks;
    vector<Location> allWorkers;
    vector<Location> allTasks;

    DataSource *load(const char *fileName, vector<Location> &vec) {
        ifstream ifs(fileName);
        if (!ifs.is_open()) {
            cout << "error read csv file: " << fileName << endl;
            exit(1);
        }
        int _;
        string id;
        string line;
        while (getline(ifs, line)) {
            stringstream ss(line);
            Location loc;
            getline(ss, id, ',');
            getline(ss, loc.lat, ',');
            getline(ss, loc.lon);
            vec.push_back(loc);
        }
        return this;
    }

    DataSource *loadTask(const char *fileName) {
        return load(fileName, allTasks);
    }

    DataSource *loadWorker(const char *fileName) {
        return load(fileName, allWorkers);
    }

    DataSource *shuffle(int seed) {
        srand(seed);
        shuffleVector(allWorkers);
        shuffleVector(allTasks);
        return this;
    }

    DataSource *allocate(int workerCount, int taskCount) {
        workers.clear();
        tasks.clear();
        for (int i = 0; i < workerCount; i++) {
            workers.push_back(allWorkers.at(i));
        }
        for (int i = 0; i < taskCount; i++) {
            tasks.push_back(allTasks.at(i));
        }
        return this;
    }

    friend ostream &operator<<(ostream &ostream, const DataSource &data) {
        ostream << "Workers(" << data.workers.size() << "):" << endl;
        for (auto w:data.workers) {
            ostream << "\t" << w << endl;
        }
        ostream << "Tasks(" << data.tasks.size() << "):" << endl;
        for (auto t:data.tasks) {
            ostream << "\t" << t << endl;
        }
        return ostream;
    }
};

#endif //LWPT_DATASOURCE_H
